//
//  SystemTabBarController.m
//  LMTabBarControllerKit
//
//  Created by mengmenglu on 6/25/16.
//  Copyright © 2016 Hangzhou TaiXuan Network Technology Co., Ltd. All rights reserved.
//

#import "SystemTabBarController.h"

@interface SystemTabBarController ()

@property (nonatomic,strong) NSArray *tabBarItems;

@end

@implementation SystemTabBarController

#pragma mark - LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUpView];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Public Method
- (id)initWithTabBarItems:(NSArray *)tabBarItems {
    self = [super init];
    if (self) {
        self.tabBarItems = tabBarItems;
        [self setUpView];
    }
    return self;
}


#pragma mark - Private Method
- (void)setUpView {
    
    if ([self.tabBarItems count] <= 0) {
        return;
    }
    
    __weak __typeof(self) weakSelf = self;
    [self.tabBarItems enumerateObjectsUsingBlock:^(STTabBarItemModel *tabBarItemModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [weakSelf configSubViewWithTabBarItemModel:tabBarItemModel];
    }];
}


- (void)configSubViewWithTabBarItemModel:(STTabBarItemModel *)tabBarItemModel {
    
    UITabBarItem *tabBarItem = [UITabBarItem new];
    tabBarItem.title = tabBarItemModel.title;
    tabBarItem.image = tabBarItemModel.normalImage;
    tabBarItem.selectedImage = tabBarItemModel.selectImage;
    [tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:TH27A1E5} forState:UIControlStateSelected];
    
    UIViewController *viewController = [[NSClassFromString(tabBarItemModel.className) alloc] init];
    viewController.title = tabBarItemModel.title;
    UINavigationController *navCtrl = [self navigationControllerWith:viewController];
    navCtrl.tabBarItem = tabBarItem;
    [self addChildViewController:navCtrl];
}


- (UINavigationController *)navigationControllerWith:(UIViewController *)viewController {
    
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        return (UINavigationController *)viewController;
    }
    
    if ([viewController isKindOfClass:[UIViewController class]]) {
        UINavigationController *navCtrl = [[UINavigationController alloc] initWithRootViewController:viewController];
        return navCtrl;
    }
    
    UIViewController *newViewController = [[UIViewController alloc] init];
    UINavigationController *newNavCtrl = [[UINavigationController alloc] initWithRootViewController:newViewController];
    return newNavCtrl;
}


@end
